import {getCurrentInstance, nextTick, ref, unref} from 'vue';
import {defHttp} from '/@/utils/http/axios';
import {useGlobSetting} from '/@/hooks/setting';
import {useMessage} from '/@/hooks/web/useMessage';
import {useUserStore} from '/@/store/modules/user';
import {sendVerifyMessage} from '/@/api/sys/msgPush';
import {TaskCode} from '/@/api/sys/model/msgPushModel';
import {thirdAuthRender, thirdUserFirstBind} from '/@/api/auth'
import {checkEmail, checkPhone} from '/@/utils/regexUtils';
import {useI18n} from '/@/hooks/web/useI18n';

export function useThirdLogin() {
  const instance = getCurrentInstance();
  const emit = instance?.emit;
  const { createMessage, notification } = useMessage();
  const { t } = useI18n();
  const glob = useGlobSetting();
  const userStore = useUserStore();
  // 授权类型
  const thirdType = ref('');
  //第三方登录相关信息
  const thirdLoginInfo = ref<any>({
    account: '', // 邮箱/手机号
    taskCode: '', // 发送邮件/短信的任务编码
    verifyCode: '', // 验证码
    password: '', // 密码(创建新账号的时候需要传)
  });
  //状态
  const thirdLoginState = ref(false);
  //绑定账号表单
  const bindingAccountForm = ref(false);
  //第三方用户UUID
  const thirdUserUuid = ref('');
  // 加载中
  const thirdBindUserLoading = ref(false);
  // 绑定用户时候的 临时访问令牌
  const accessToken = ref<string>('')
  const loginId = ref();
  // 首页多租户部门弹窗逻辑
  const loginSelectRef = ref();
  // 注册并绑定表单
  const registerAndBindForm = ref(false)

  async function onThirdAuthRender(grantType) {
    const data = await thirdAuthRender(grantType)
    window.location.href = data.pageUrl
  }

  function showBindAccount() {
    registerAndBindForm.value = false;
    bindingAccountForm.value = true;
  }

  function showRegisterAndBindAccount() {
    registerAndBindForm.value = true;
    bindingAccountForm.value = false;
  }

  //第三方登录
  async function onThirdLogin(loginData) {
    const { grantType, clientId } = loginData
    thirdType.value = grantType;
    thirdLoginInfo.value = {};
    thirdLoginState.value = false;
    accessToken.value = loginData.authToken?.accessToken

    if (!loginData.authToken?.accessToken) {
      requestFailed({ message: '登录失败' })
      return false
    } 
    if (loginData.isBind) {
      doThirdLogin(loginData);
    } else {
      bindingAccountForm.value = true;
    } 
    return true
  }

  // 登录成功之后先跳出用户租户选择, 选择成功之后执行最后的登录逻辑
  function handleLoginSelectOk(switchTenant : any, menuLoadingKey) {
    console.log('login success - SelectTenant ', switchTenant);
    nextTick(() => {
      try {
        if (switchTenant) {
          setTimeout(() => {
            notification.success({
              message: t('sys.login.loginSuccessTitle'),
              description: `${t('sys.login.loginSuccessDesc')}: ${switchTenant.realName}`,
              duration: 3,
            });
          }, 2000)
          userStore.setToken(accessToken.value)
          userStore.afterLoginAction(true, {})
        }
      } finally {
        setTimeout(() => createMessage.destroy(menuLoadingKey), 500)
      }
      emit?.('loginSuccess')
    });
  }

  // 根据token执行登录
  function doThirdLogin(authToken) {
    // 先打开租户选择弹窗
    accessToken.value = authToken.accessToken
    loginId.value = authToken.loginId

    nextTick(() => {
      emit?.('loginBefore')
      loginSelectRef.value.show({accessToken: unref(accessToken), loginId: unref(loginId)})
    });
  }

  function requestFailed(err) {
    notification.error({
      message: '登录失败',
      description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
      duration: 4,
    });
  }

  //创建新账号并绑定
  function thirdRegisterAndBindUser() {

  }
  
  // 绑定存在的用户
  function thirdBindExistUser() {
    thirdBindUserLoading.value = true;
    thirdUserFirstBind({...unref(thirdLoginInfo), accessToken: accessToken.value}).then((res) => {
      if (res.success) {
        console.log('bind success', res.data);
        doThirdLogin(res.data);
      } else {
        requestFailed(res)
      }
    }).finally(() => {
      thirdBindUserLoading.value = false;
    });
  }

  // 发送验证码
  async function sendCodeApi(data? : any) {
    const form = unref(thirdLoginInfo)
    if (!checkEmail(form.account) && !checkPhone(form.account)) {
      createMessage.error('请输入正确的手机号或者邮箱')
      return
    }

    console.log('data', data)
    thirdLoginInfo.value.taskCode = checkEmail(form.account) ? TaskCode.VERIFY_EMAIl : TaskCode.VERIFY_SMS
    await sendVerifyMessage({
      toUser: unref(thirdLoginInfo).account,
      bizType: 'login',
      taskCode: thirdLoginInfo.value.taskCode,
      uuid: data.uuid,
      imageCaptcha: data?.imageCaptcha
    })
    return true
  }

  //绑定手机号点击确定按钮
  function thirdHandleOk() {
    const form = unref(thirdLoginInfo)
    if (!checkEmail(form.account) && !checkPhone(form.account)) {
      createMessage.error('请输入正确的手机号或者邮箱')
      return
    } 
    if (!form.captcha) {
      cmsFailed('请输入验证码');
    }
    let params = {
      mobile: form.account,
      captcha: form.captcha,
      thirdUserUuid: unref(thirdUserUuid),
    };
    defHttp.post({ url: '/sys/thirdLogin/bindingThirdPhone', params }, { isTransformResponse: false }).then((res) => {
      if (res.success) {
        bindingAccountForm.value = false;
        doThirdLogin(res.result);
      } else {
        createMessage.warning(res.message);
      }
    });
  }

  function cmsFailed(err) {
    notification.error({
      message: '登录失败',
      description: err,
      duration: 4,
    });
    return;
  }

  //返回数据和方法
  return {
    thirdBindUserLoading,
    thirdBindExistUser,
    bindingAccountForm,
    thirdHandleOk,
    onThirdLogin,
    thirdLoginInfo,
    sendCodeApi,
    onThirdAuthRender,
    registerAndBindForm,
    thirdRegisterAndBindUser,
    showBindAccount,
    showRegisterAndBindAccount,
    handleLoginSelectOk,
    loginSelectRef
  };
}
